package org.blog.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.blog.config.UrlConfig;
import org.blog.helper.Constants;
import org.blog.helper.HttpUtils;
import org.blog.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoggerInterceptor implements HandlerInterceptor {

	@Autowired
	private UrlConfig urlConfig;

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	private String getUser(HttpSession session) {
		return null;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		HttpUtils.preventCaching(response);
		
		// 对所有操作日志进行记录
		String cookieValue = cookieValue(findCookie(request));
		if (cookieValue != null) {
			String path=request.getServletPath();
			
			String user = getUser(request.getSession());
			StringBuilder builder = new StringBuilder();
			builder.append("[sid:").append(cookieValue);
			builder.append(",user:").append(StringHelper.nullToStr(user));
			builder.append("] visit ").append(urlConfig.getChinaServiceName(path)).append(" at ")
					.append(System.currentTimeMillis() / 1000).append(". With the data id :");
			//TODO builder.append("");
//			serviceLog.log(builder.toString());
		}

	}

	private Cookie findCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (Constants.COOKIE_NAME.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	private String cookieValue(Cookie cookie) {
		if (cookie != null) {
			return cookie.getValue();
		}
		return null;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		

		return true;
	}

}
